const { obd_collection } = require('../config')
const { region_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const department = require('../action/department');
// 通过获取所有obd经纬度计算网格内的obd中心点
exports.main = async (event, context) => {

    var i = 0;
    for (region of department.regions) {
        i++;
        console.log(department.regions.length, i, '开始更新区域：' + region)
        // 2.在obd信息表中查找到该员工账号的obd，获取所有obd的经纬度；无经obd则下一个
        const sum = await db.collection(obd_collection).where({ region: region }).count();
        const pageSize = 1000;
        const pageSum = Math.ceil(sum.total / pageSize);
        var page = 0;
        var failregions = [];
        while (page < pageSum) {
            let obdData = await db.collection(obd_collection).where({ region: region }).skip(page * pageSize).limit(pageSize).get();
            page++;
            allregionLongLat = [];
            for (obd of obdData.data) {
                if (obd.long && obd.lat) {
                    allregionLongLat.push({ lng: Number(obd.long), lat: Number(obd.lat) });
                }
            }
            var mapData = cal(allregionLongLat);
            let regionCount = await db.collection(region_collection).where({ region: region }).count();
            if(regionCount.total == 0){
                let upRes = await db.collection(region_collection).add({ region: region, center: mapData.center });
                if (!upRes) {
                    failregions.push(region);
                    console.log(i, region + '增加失败')
                }
            }else{
                let upRes = await db.collection(region_collection).where({ region: region }).update({ center: mapData.center });
                if (!upRes) {
                    failregions.push(region);
                    console.log(i, region + '更新失败')
                }
            }
            
        }
    }
    return { sumregion: department.regions.length, failregions: failregions }
    // 保存接口日志
    // let apiLog = {
    //     "target": event.target,
    // }
}
function cal(allObdLongLat) {
    const convexHull = require('convex-hull');

    // 转换数据格式为凸包库需要的形式
    const points = allObdLongLat.map(p => [parseFloat(p.lng), parseFloat(p.lat)]);
    // 计算凸包
    const hull = convexHull(points);

    // 创建一个空数组来存储凸包上的点
    let hullPoints = [];

    // 添加每条边的起始点
    for (let i = 0; i < hull.length; i++) {
        let idx = hull[i][0]; // 获取边的起始点索引
        hullPoints.push({ lng: points[idx][0], lat: points[idx][1] });
    }

    // 确保多边形闭合，检查第一个和最后一个点是否相同，如果不相同，添加第一个点到末尾
    if (hullPoints[0].lng !== hullPoints[hullPoints.length - 1].lng ||
        hullPoints[0].lat !== hullPoints[hullPoints.length - 1].lat) {
        hullPoints.push(hullPoints[0]);
    }

    // 计算中心点（质心）
    let centerX = 0;
    let centerY = 0;
    hullPoints.forEach(point => {
        centerX += point.lng;
        centerY += point.lat;
    });
    centerX /= hullPoints.length;
    centerY /= hullPoints.length;

    // 输出结果
    // console.log('Hull Points:', hullPoints);
    // console.log('Perimeter:', perimeter);
    // console.log('Area:', area);
    // console.log('Center Point:', { lng: centerX, lat: centerY });

    return { 'center': { lng: centerX, lat: centerY } };
}
// {"obdLongLat":[{"lng":"110.921983","lat":"21.676655"},{"lng":"110.949211","lat":"21.679529"},{"lng":"110.945905","lat":"21.685037"},{"lng":"110.932512","lat":"21.672313"},{"lng":"110.930776","lat":"21.681453"},{"lng":"110.917828","lat":"21.661672"},{"lng":"110.929164","lat":"21.693888"},{"lng":"110.942564","lat":"21.672544"},{"lng":"110.939894","lat":"21.68074"}]用nodejs处理我给出的这些x、y轴点数据（lng对应x轴，lat对应y轴），对他们进行排序、筛选，让处理后的x、y点的点连接起来后形成一个闭合的只有凸包没有凹包的多边形，这个要求意味着可以舍弃部分不符合要求的点，请您按照要求给出详细的nodejs代码

// 有必要给计算面积功能做日志记录吗？如果